<template>
  <div class="page-point-clock">
    <common-head :showIcon="false"></common-head>
    <van-overlay :show="overShow">
      <div class="loading-container">
        <van-loading size="24px" type="spinner" vertical>加载中...</van-loading>
      </div>
    </van-overlay>
    <!-- 添加一个弹出层 -->
    <div class="new-clock" :style="{ display: initMapShow }">
      <!-- 用户信息 -->
      <div class="user-info">
        <div class="user-info-item">
          <div class="user-avatar">
            <img :src="userInfoAvatar" alt="头像" />
          </div>
          <div class="user-desc">
            <div class="user-name">{{ userInfo.username }}</div>
            <div class="user-work-no">{{ userInfo.phone }}</div>
          </div>
        </div>
        <div class="user-action" @click="getOutClock">
          <img src="../../assets/img/apply.png" alt="头像" />
          <span>外勤</span>
        </div>
      </div>

      <!-- 打卡详情 -->
      <div class="clock-detail">
        <div class="clock-time">
          <div class="detail-item">
            <div class="clock-time-item">
              <div class="label">上班</div>
              <div class="value">
                {{ inspectionShiftList.allowStartClockIn }}
              </div>
            </div>
            <div class="today-clock-time">
              <van-radio
                :icon-size="12"
                v-model="attendanceStatusUp"
                disabled
                name="1"
                shape="dot"
              >
                <span class="today-clock-time-text">
                  <span
                    class="today-clock-time-text"
                    v-if="attendanceStatusUp == 1"
                  >
                    {{ attendanceStatusUpTime }}已打卡</span
                  >
                  <span class="today-clock-time-text" v-else>未打卡</span>
                </span>
              </van-radio>
            </div>
          </div>
          <div class="detail-item">
            <div class="clock-time-item">
              <div class="label">下班</div>
              <div class="value">
                {{ inspectionShiftList.allowEndClockOut }}
              </div>
            </div>
            <div class="today-clock-time">
              <van-radio
                :icon-size="12"
                disabled
                v-model="attendanceStatusDown"
                name="1"
                shape="dot"
              >
                <span class="today-clock-time-text">
                  <span
                    class="today-clock-time-text"
                    v-if="attendanceStatusDown == 1"
                    >{{ attendanceStatusDownTime }}已打卡</span
                  >
                  <span class="today-clock-time-text" v-else>未打卡</span>
                </span>
              </van-radio>
            </div>
          </div>
        </div>
        <div class="clock-action">
          <div class="clock-button" @click="pointClock">
            <van-loading v-if="clockLoading" size="20px" />
            <span v-else>{{ clockText }}</span>
          </div>

          <div class="location-info">
            <p>
              {{ userInfo.username }} 正在
              {{ isOutWork ? "外勤打卡" : currenntAddress || "暂无定位" }}
            </p>
            <p :class="isOutWork ? 'out-range' : 'in-range'">
              {{ isOutWork ? "❌ 超出考勤范围 " : "✅ 考勤范围内" }}
            </p>
          </div>
        </div>
      </div>
    </div>
    <div id="map-container"></div>
    <div class="user-active">
      <div class="user-active-btn">
        <div class="user-active-btn-item">
          <div class="tip-text" @click="showPlockTotal">
            统计
          </div>
          <div
            @click="restAdress"
            class="tip-text clock-center active-bottom-nav"
          >
            打卡
          </div>

          <div class="tip-text" @click="showMap">
            地图
          </div>
        </div>
      </div>
    </div>
    <!-- 添加一个弹窗 -->
    <van-calendar
      v-model="show"
      :min-date="minDate"
      :formatter="formatter"
      title="打卡统计"
      :allow-html="true"
      :max-date="maxDate"
      @confirm="onConfirm"
      @select="onCalendarSelect"
      @close="onClose"
    />

    <!-- 外勤打卡弹窗 -->
    <van-dialog
      v-model:show="outClockDialog"
      title="申请外勤"
      show-cancel-button
      :before-close="beforeClose"
      :show-confirm-button="true"
      confirm-button-text="提交"
    >
      <van-overlay :show="isUploadDisabled">
        <div class="loading-container">
          <van-loading size="24px" type="spinner" vertical
            >图片上传中...</van-loading
          >
        </div>
      </van-overlay>

      <div class="outwork-application">
        <!-- 外勤时间 -->
        <van-cell-group inset>
          <van-field name="time" label="外勤时间">
            <template #input>
              <span class="time-display">{{ outWorkTime }}</span>
            </template>
          </van-field>

          <!-- 申请理由 -->
          <van-field
            v-model="reasonForOutWork"
            rows="2"
            autosize
            label="申请理由"
            type="textarea"
            maxlength="100"
            placeholder="请输入申请理由"
            show-word-limit
          />

          <!-- 上传图片 -->
          <van-field label="上传图片">
            <template #input>
              <van-uploader
                v-model="outWorkImages"
                :after-read="onAfterReadImage"
              />
            </template>
          </van-field>
        </van-cell-group>
      </div>
    </van-dialog>

    <!-- 打卡统计弹窗 -->
    <van-dialog
      v-model:show="clockRecordsShow"
      title="当日打卡情况"
      show-cancel-button
      :close-on-click-overlay="true"
    >
      <div class="dialog-content">
        <!-- 多条打卡记录列表 -->
        <div v-if="currentRecord.length > 0" class="record-list">
          <div
            v-for="(record, index) in currentRecord"
            :key="index"
            class="record-item"
          >
            <div class="record-title">
              打卡时间：{{ record.actualSignTime }}
            </div>
            <div class="record-details">
              <p><strong>地点：</strong>{{ record.address || "暂无" }}</p>
              <p>
                <strong>经纬度：</strong>{{ record.signLatitude }},
                {{ record.signLongitude }}
              </p>
              <p>
                <strong>图片：</strong>
                <img
                  v-if="record.signImagePath"
                  :src="record.signImagePath"
                  alt="打卡图片"
                  style="width: 80px; height: 80px; object-fit: cover;"
                />
                <span v-else>无图片</span>
              </p>
            </div>
          </div>
        </div>
        <div v-else class="no-record">暂无打卡记录</div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import commonHead from "../../components/xc/commonHead.vue";
import { MapClient } from "@/service/common/baseService";
import setting from "@/setting";
export default {
  name: "TencentMap",
  components: {
    commonHead
  },
  data() {
    return {
      clockLoading: false,
      // 当前的经度位置
      longitude: 0,
      // 当前的纬度位置
      latitude: 0,
      show: false,
      minDate: (() => {
        const date = new Date();
        date.setDate(1); // 设置为当前月份的第一天
        return date;
      })(),
      maxDate: new Date(),
      // 签到数据
      buildClockData: {},
      // 是否已经打了上班的卡
      isReadySignIn: false,
      // 是否为外勤
      isOutWork: false,
      // 当前时间 和 时间戳
      currentTimeAndTimestamp: {},
      // 可以开始打卡的时间 和 时间戳
      startTimeAndTimestamp: {},
      // 可以结束打卡的时间 和 时间戳
      endTimeAndTimestamp: {},
      // 打卡记录
      clockRecord: [],
      // 班次列表
      inspectionShiftList: [],
      // 当前定位地址
      currenntAddress: "",
      userInfo: {},
      // 遮罩层
      overShow: false,
      popupShow: true,
      initMapShow: "block",
      outClockDialog: false,
      attendanceStatusUp: "0", // 默认未打卡
      attendanceStatusDown: "0",
      attendanceStatusUpTime: "00:00:00",
      attendanceStatusDownTime: "00:00:00",
      // 外勤理由
      reasonForOutWork: "",
      outWorkTime: this.getCurrentTime(),
      outWorkImages: [],
      outWorkImagesUrl: [],
      clockRecordsShow: false,
      // 选择日期的打卡记录
      currentRecord: [],
      userInfoAvatar: "",
      clockText: "上班打卡",
      isUploadDisabled: false
    };
  },
  mounted() {
    this.getLocation();
    this.getInspectionShiftList();
    this.getTodayClockRecord();
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.userInfoAvatar =
      setting.ctx +
      "/user-center/sys/common/static/" +
      JSON.parse(localStorage.getItem("userInfo")).avatar;
  },

  methods: {
    // 外勤上传图片
    onAfterReadImage(file) {
      this.isUploadDisabled = true;
      const formData = new FormData();
      formData.append("biz", "temp");
      formData.append("file", file.file);
      this.baseService
        .post("/user-center/sys/common/upload", formData)
        .then(res => {
          console.log("res---->", res);
          this.isUploadDisabled = false;
          if (res.code == 0) {
            this.buildClockData = {};
            this.outWorkImagesUrl.push(res.message);
            this.buildClockData.validFlag = this.reasonForOutWork;
            this.$toast.success("上传成功");
          } else {
            this.$toast.fail("上传失败");
          }
        });
    },

    beforeClose(action, done) {
      if (action == "confirm" && this.reasonForOutWork == "") {
        this.$toast.fail("请填写申请理由");
        done(false);
        return;
      } else if (action == "confirm" && this.outWorkImagesUrl.length == 0) {
        this.$toast.fail("请上传图片");
        done(false);
        return;
      } else if (action == "confirm") {
        this.submitOutWorkApplication();
        done();
      }
      if (action == "cancel") {
        done();
      }
    },
    // 外勤提交打卡
    submitOutWorkApplication() {
      this.getInspectionShiftSetting("waiqin");
    },
    // 获取当天日期时间范围
    getCurrentDayRange() {
      const now = new Date();

      // 设置时间为当天 00:00:00
      const startOfDay = new Date(now);
      startOfDay.setHours(0, 0, 0, 0);

      // 设置时间为当天 23:59:59
      const endOfDay = new Date(now);
      endOfDay.setHours(23, 59, 59, 999);

      // 格式化函数
      const formatDate = date => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      return {
        startTime: formatDate(startOfDay),
        endTime: formatDate(endOfDay)
      };
    },
    // 获取当天的打卡记录
    getTodayClockRecord() {
      const dayRange = this.getCurrentDayRange();
      this.baseService
        .get(
          `/parking/inspectionSignRecord/page?createTime_begin=${dayRange.startTime}&createTime_end=${dayRange.endTime}`
        )
        .then(res => {
          console.log("res--当天巡查打卡记录-->", res);
          console.log(
            "res-获取到当天的巡查记录--->",
            res.result.records.length
          );
          if (res.result.records.length == 1) {
            this.attendanceStatusUp = "1";
            this.attendanceStatusUpTime = res.result.records[0].actualSignTime;
          } else if (res.result.records.length > 1) {
            this.attendanceStatusUp = "1";
            this.attendanceStatusUpTime = res.result.records[0].actualSignTime;
            this.attendanceStatusDown = "1";
            this.attendanceStatusDownTime =
              res.result.records[res.result.records.length - 1].actualSignTime;
          }
        });
    },
    // 打开外勤打卡弹窗
    getOutClock() {
      this.outWorkTime = this.getCurrentTime();
      this.outWorkImages = [];
      this.reasonForOutWork = "";
      this.outClockDialog = true;
    },
    // 展示地图
    showMap() {
      this.initMapShow = "none";
      this.show = false;
      // 将 类名 active-bottom-nav 移出 并给自己加上
      document
        .querySelectorAll(".user-active-btn-item .tip-text")
        .forEach(el => {
          el.classList.remove("active-bottom-nav");
        });
      event.currentTarget.classList.add("active-bottom-nav");
    },
    showPlockTotal() {
      this.show = true;
      this.getInspectionSignRecord();
      document
        .querySelectorAll(".user-active-btn-item .tip-text")
        .forEach(el => {
          el.classList.remove("active-bottom-nav");
        });
      event.currentTarget.classList.add("active-bottom-nav");
    },
    onClose() {
      this.restAdress();
      document
        .querySelectorAll(".user-active-btn-item .tip-text")
        .forEach(el => {
          el.classList.remove("active-bottom-nav");
        });
      let clockCenter = document.querySelector(".clock-center");
      clockCenter.classList.add("active-bottom-nav");
    },
    restAdress() {
      this.show = false;
      this.getLocation();
      this.initMapShow = "block";
      document
        .querySelectorAll(".user-active-btn-item .tip-text")
        .forEach(el => {
          el.classList.remove("active-bottom-nav");
        });
      event.currentTarget.classList.add("active-bottom-nav");
    },
    // 获取班次设置列表
    async getInspectionShiftList() {
      let username = JSON.parse(localStorage.getItem("userInfo")).username;
      try {
        const res = await this.baseService.get(
          `/parking/inspectionShiftSetting/page?createBy=${username}`
        );
        console.log("res-获取班次列表--1111->", res.result.records[0]);
        if (
          res.result.records[0] == null ||
          res.result.records[0] == undefined
        ) {
          this.$toast.fail("获取班次列表失败");
          this.overShow = false;
          return;
        }
        this.inspectionShiftList = res.result.records[0];
        console.log("inspectionShiftList::: ", this.inspectionShiftList);
      } catch (error) {
        console.error("获取员工班次信息失败", error);
        this.$toast.fail("获取员工班次信息失败");
      }
    },
    // 打卡统计 查询单个日期的打卡记录
    onConfirm() {},
    onCalendarSelect(val) {
      this.clockRecordsShow = true;
      const formatDateTime = date => {
        const YYYY = date.getFullYear();
        const MM = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
        const DD = String(date.getDate()).padStart(2, "0");
        const HH = String(date.getHours()).padStart(2, "0");
        const mm = String(date.getMinutes()).padStart(2, "0");
        const ss = String(date.getSeconds()).padStart(2, "0");
        return {
          startTime: `${YYYY}-${MM}-${DD} ${HH}:${mm}:${ss}`,
          endTime: `${YYYY}-${MM}-${DD} 23:59:59`
        };
      };

      const formattedDate = formatDateTime(val);
      console.log("格式化后的日期:", formattedDate); // 输出示例：
      this.baseService
        .get(
          `/parking/inspectionSignRecord/page?createTime_begin=${formattedDate.startTime}&createTime_end=${formattedDate.endTime}`
        )
        .then(res => {
          console.log("res-统计中单个日期的打卡---->", res);
          this.currentRecord = res.result.records.filter(
            item => item.actualSignTime
          );
        });
    },

    // 获取班次设置列表
    async getInspectionShiftSetting(type) {
      try {
        const res = await this.baseService.get(
          "/parking/inspectionShiftSetting/page?createBy=admin"
        );

        console.log("res-获取班次设置--->", res.result.records[0]);
        this.buildClockData = res.result.records[0];

        // 允许开始打卡的时间戳
        console.log(
          "允许开始打卡时间---->",
          this.buildClockData.allowStartClockIn
        );
        let allowStartClockInTimestamp = this.returnTimestamp(
          this.buildClockData.allowStartClockIn
        );
        console.log("允许开始打卡时间的时间戳::: ", allowStartClockInTimestamp);
        this.startTimeAndTimestamp = allowStartClockInTimestamp;

        // 允许结束打卡的时间戳
        console.log(
          "允许结束打卡时间---->",
          this.buildClockData.allowEndClockOut
        );
        let allowEndClockOutTimestamp = this.returnTimestamp(
          this.buildClockData.allowEndClockOut
        );
        console.log("允许结束打卡时间::: ", allowEndClockOutTimestamp);
        this.endTimeAndTimestamp = allowEndClockOutTimestamp;

        // 获取当前的时间戳
        let now = new Date();
        let hours = String(now.getHours()).padStart(2, "0");
        let minutes = String(now.getMinutes()).padStart(2, "0");
        let seconds = String(now.getSeconds()).padStart(2, "0");
        let currentTime = `${hours}:${minutes}:${seconds}`;
        let nowTimestamp = this.returnTimestamp(currentTime);
        this.currentTimeAndTimestamp = nowTimestamp;

        console.log("当前时间的时间戳::: ", nowTimestamp);

        if (type == "waiqin") {
          console.log("外勤打卡---->");
          this.buildClockRecord();
          return;
        }

        // 打卡的逻辑判断
        if (nowTimestamp.timestamp <= allowStartClockInTimestamp.timestamp) {
          // this.$toast.fail("可以打卡-早上的卡");
          this.buildClockRecord();
        } else if (
          nowTimestamp.timestamp >= allowEndClockOutTimestamp.timestamp
        ) {
          // this.$toast.fail("可以打卡-晚上的卡");
          this.buildClockRecord();
        } else {
          this.outClockDialog = true;
          this.outWorkTime = this.getCurrentTime();
          this.$message.error("不在考勤时间范围内，请打外勤卡");
        }
      } catch (error) {
        console.error("获取员工班次信息失败", error);
        this.$toast.fail("获取员工班次信息失败");
      }
    },

    //! 提供一个方法 传入时间 返回时间戳
    returnTimestamp(time) {
      const timeArray = time.split(":");
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const allTime = `${year}-${month}-${day} ${timeArray[0]}:${timeArray[1]}:${timeArray[2]}`;
      console.log("转换后的时间::: ", allTime);
      // return this.toUTCTimestamp(allTime);
      return {
        timestamp: this.toUTCTimestamp(allTime),
        time: allTime
      };
    },

    //! 将标准时间转换为时间戳
    toUTCTimestamp(dateString) {
      const formattedDate = dateString.replace(/-/g, "/");
      const dateObj = new Date(formattedDate);
      return Math.floor(dateObj.getTime() / 1000);
    },

    // 查询签到记录
    getInspectionSignRecord() {
      // 获取当前年 当前月 当前月的第一天零点 和 当前月的最后一天23:59:59

      function getCurrentMonthRange() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, "0");

        // 当前月第一天
        const firstDay = new Date(year, now.getMonth(), 1);
        firstDay.setHours(0, 0, 0, 0);

        // 当前月最后一天
        const lastDay = new Date(year, now.getMonth() + 1, 0);
        lastDay.setHours(23, 59, 59, 999);

        const formatDateTime = date => {
          const YYYY = date.getFullYear();
          const MM = String(date.getMonth() + 1).padStart(2, "0");
          const DD = String(date.getDate()).padStart(2, "0");
          const HH = String(date.getHours()).padStart(2, "0");
          const mm = String(date.getMinutes()).padStart(2, "0");
          const ss = String(date.getSeconds()).padStart(2, "0");
          return `${YYYY}-${MM}-${DD} ${HH}:${mm}:${ss}`;
        };

        return {
          currentYear: year,
          currentMonth: Number(now.getMonth() + 1),
          firstDay: formatDateTime(firstDay),
          lastDay: formatDateTime(lastDay)
        };
      }

      const {
        currentYear,
        currentMonth,
        firstDay,
        lastDay
      } = getCurrentMonthRange();
      console.log(`当前月的第一天零点: ${firstDay}`);
      console.log(`当前月的最后一天23:59:59: ${lastDay}`);

      this.baseService
        .get(
          `/parking/inspectionSignRecord/page?createTime_begin=${firstDay}&createTime_end=${lastDay}`
        )
        .then(res => {
          console.log("res-查询签到记录--->", res);
          this.clockRecord = res.result.records;
        });
    },

    // 计算迟到时长问题
    calculateDelayMinutes(time1, time2) {
      const [h1, m1, s1] = time1.split(":").map(Number);
      const [h2, m2, s2] = time2.split(":").map(Number);

      const timestamp1 = h1 * 3600 + m1 * 60 + s1;
      const timestamp2 = h2 * 3600 + m2 * 60 + s2;

      return Math.floor((timestamp1 - timestamp2) / 60); // 返回分钟差
    },
    // 新建一个打卡记录
    buildClockRecord() {
      this.buildClockData = {};
      console.log("this.outWorkImagesUrl---->", this.outWorkImagesUrl);
      if (this.outWorkImagesUrl.length > 0) {
        this.buildClockData.signImagePath = this.outWorkImagesUrl[0];
      }
      this.buildClockData.validFlag = this.reasonForOutWork;
      this.buildClockData.actualSignTime = this.currentTimeAndTimestamp.time.split(
        " "
      )[1];
      this.buildClockData.allowedSignEndTime = this.endTimeAndTimestamp.time.split(
        " "
      )[1];
      this.buildClockData.allowedSignStartTime = this.startTimeAndTimestamp.time.split(
        " "
      )[1];
      this.buildClockData.lateDurationMinutes = 0;
      this.buildClockData.overtimeDurationMinutes = 0;
      this.buildClockData.signStatus = 1;
      this.buildClockData.deviceId = "000000000000";
      this.buildClockData.signType = 1;
      this.buildClockData.signSource = "PDA";
      this.buildClockData.address = this.currenntAddress;

      // 经度
      this.buildClockData.signLongitude = this.longitude;
      // 纬度
      this.buildClockData.signLatitude = this.latitude;
      this.buildClockData.signType = 1;
      this.buildClockData.updateBy = JSON.parse(
        localStorage.getItem("userInfo")
      ).username;
      this.buildClockData.updateTime = this.currentTimeAndTimestamp.time;
      this.buildClockData.userId = JSON.parse(
        localStorage.getItem("userInfo")
      ).id;

      console.log(
        "this.buildClockData--打卡的参数-暂时注释打卡->",
        this.buildClockData
      );
      this.baseService
        .post("/parking/inspectionSignRecord/add", this.buildClockData)
        .then(res => {
          console.log("res-新建一个打卡记录--->", JSON.stringify(res));
          if (res.code !== 200) {
            this.$toast({
              message: res.msg,
              type: "error"
            });
            this.clockLoading = false;
          } else {
            this.$toast({
              message: "打卡成功"
            });
            this.clockLoading = false;
          }
        });
    },
    formatter(day) {
      const month = day.date.getMonth() + 1;

      const date = day.date.getDate();
      let recordList = [];
      const today = new Date().getDate();
      // 当日期小于今天 默认添加两个蓝色的点 代表默认打卡
      // 后续 获取接口 将未打卡的日期 添加一个橙色点
      if (date <= today) {
        day.className = "addBlueDotLeft addBlueDotRight";
      }

      for (let i = 0; i < this.clockRecord.length; i++) {
        if (
          date == this.clockRecord[i].createTime.split(" ")[0].split("-")[2]
        ) {
          recordList.push(this.clockRecord[i]);
        }
      }
      if (recordList.length == 0 && date <= today) {
        day.className = "addRedDotLeft addRedDotRight";
      }
      if (recordList.length == 1 && date <= today) {
        day.className = "addBlueDotLeft addRedDotRight";
      }
      if (recordList.length >= 2 && date <= today) {
        day.className = "addBlueDotLeft addBlueDotRight";
      }

      return day;
    },

    // 测试考勤接口
    testClock() {
      this.baseService
        .get("/parking/inspectionStaffAttendance/page")
        .then(res => {
          console.log(res, "考勤结果");
        });
    },
    pointClock() {
      this.clockLoading = true;
      setTimeout(() => {
        this.clockLoading = false;
      }, 2000);
      if (this.isOutWork) {
        this.outClockDialog = true;
        this.outWorkTime = this.getCurrentTime();
        this.$message.error("不在考勤范围内，请打外勤卡");
      } else {
        this.getInspectionShiftSetting();
      }
    },

    async initMap() {
      // todo 线上环境
      // this.longitude = 114.684423;
      // this.latitude = 27.821859;
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      var that = this;
      console.log("that.userInfo.id::: ", that.userInfo.id);

      //#region  渲染地图部分
      var center = new TMap.LatLng(that.latitude, that.longitude);
      var map = new TMap.Map(document.getElementById("map-container"), {
        center: center, //设置地图中心点坐标
        zoom: 18, //设置地图缩放级别
        pitch: 43.5, //设置俯仰角
        rotation: 45 //设置地图旋转角度
      });
      //创建并初始化MultiMarker
      var markerLayer = new TMap.MultiMarker({
        map: map, //指定地图容器
        //样式定义
        styles: {
          myStyle: new TMap.MarkerStyle({
            width: 25, // 点标记样式宽度（像素）
            height: 25, // 点标记样式高度（像素）
            src: require("../../assets/img/mark.png"), //图片路径
            anchor: { x: 16, y: 32 }
          })
        },
        // 点标记数据
        geometries: [
          {
            id: "1", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            styleId: "myStyle", //指定样式id
            position: new TMap.LatLng(that.latitude, that.longitude), //点标记坐标位置
            properties: {
              //自定义属性
              title: "marker1"
            }
          }
        ]
      });
      //#endregion

      if (document.getElementById("map-container").children.length > 0) {
        this.overShow = false;
        if (that.longitude && that.latitude) {
          // 获取绑定的停车场信息
          try {
            const res = await that.baseService.get(
              `/parking/inspectionUserParking/queryByUserId?userId=${that.userInfo.id}`
            );
            console.log("-绑定的停车场信息--->", JSON.stringify(res));
            console.log("绑定的停车场信息id-->", res.result.parkingLotIds);
            if (
              res.result.parkingLotIds == null ||
              res.result.parkingLotIds == undefined
            ) {
              this.$toast({
                message: "该用户没有绑定停车场"
              });
              this.overShow = false;
              this.isOutWork = true;
              this.clockText = "外勤打卡";
              return;
            }
            if (res.result.parkingLotIds.includes(",")) {
              //#region 负责多个停车场
              that.parkingLotIds = res.result.parkingLotIds.split(",");
            } else {
              that.parkingLotIds = [res.result.parkingLotIds];
            }
            console.log("that.parkingLotIds::: ", that.parkingLotIds);

            let inRangeList = [];
            for (let i = 0; i < that.parkingLotIds.length; i++) {
              try {
                const res = await that.baseService.get(
                  `/parking/bizParkingLots/queryById?id=${that.parkingLotIds[i]}`
                );
                if (res.code != 200) {
                  that.$toast("获取绑定停车场失败");
                  this.isOutWork = true;
                  this.clockText = "外勤打卡";
                  return;
                }
                // 强制转换为 Number 类型
                const latitude = Number(res.result.latitude);
                const longitude = Number(res.result.longitude);

                //#region  创建打卡范围的标记
                var markerLayer = new TMap.MultiMarker({
                  map: map, //指定地图容器
                  //样式定义
                  styles: {
                    //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
                    myStyle: new TMap.MarkerStyle({
                      width: 25, // 点标记样式宽度（像素）
                      height: 25, // 点标记样式高度（像素）
                      src: require("../../assets/img/markIn.png"), //图片路径
                      //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                      anchor: { x: 16, y: 32 }
                    })
                  },
                  //点标记数据数组
                  geometries: [
                    {
                      id: "1", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                      styleId: "myStyle", //指定样式id
                      position: new TMap.LatLng(
                        res.result.latitude,
                        res.result.longitude
                      ), //点标记坐标位置
                      properties: {
                        //自定义属性
                        title: "marker1"
                      }
                    }
                  ]
                });

                // 创建范围
                var circle = new TMap.MultiCircle({
                  map,
                  styles: {
                    // 设置圆形样式
                    circle: new TMap.CircleStyle({
                      color: "rgba(41,91,255,0.16)",
                      showBorder: true,
                      borderColor: "rgba(41,91,255,0.5)",
                      borderWidth: 1
                    })
                  },
                  geometries: [
                    {
                      styleId: "circle",
                      center: new TMap.LatLng(
                        res.result.latitude,
                        res.result.longitude
                      ), //圆形中心点坐标
                      radius: 100 //半径（单位：米） 设置打卡半径
                    }
                  ]
                });
                //#endregion

                try {
                  // const res = await MapClient.get(
                  //   `https://apis.map.qq.com/ws/distance/v1?key=46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5&from=${that.latitude},${that.longitude}&to=${latitude},${longitude}&mode=walking`
                  // );
                  // todo 线上环境
                  const res = await this.baseService.get(
                    `https://apis.map.qq.com/ws/distance/v1/?key=46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5&from=${that.latitude},${that.longitude}&to=${latitude},${longitude}&mode=walking`
                  );
                  console.log("--计算距离信息-->", JSON.stringify(res));
                  console.log(
                    "res.data.result.elements[0].distance::: ",
                    res.result.elements[0].distance
                  );
                  if (res.result.elements[0].distance < 300) {
                    inRangeList.push(res.result.elements[0].distance);
                  }
                } catch (error) {
                  console.log("error::: ", error);
                  console.log("---->", JSON.stringify(error));
                  this.$toast.fail("计算打卡距离失败");
                }
              } catch (error) {
                this.$toast.fail("获取绑定停车场信息失败");
                this.isOutWork = true;
                this.clockText = "外勤打卡";
              }
            }
            console.log("inRangeList:距离总长度: ", inRangeList);
            if (inRangeList.length > 0) {
              // this.$toast("考勤范围内1111");
              that.isOutWork = false;
              if (that.attendanceStatusUp == 1) {
                this.clockText = "下班打卡";
              } else {
                this.clockText = "上班打卡";
              }
            } else {
              // this.$toast.fail("考勤范围外22222");
              that.isOutWork = true;
              this.clockText = "外勤打卡";
            }
          } catch (error) {
            this.$toast.fail("获取用户绑定的停车场信息失败");
            console.log("error---->", error);
          }
        }
      } else {
        that.$toast({
          message: "地图初始化失败",
          duration: 1500
        });
        this.overShow = false;
      }

      document.getElementById("map-container").addEventListener(
        "touchstart",
        function(e) {
          e.preventDefault(); // 需要时才调用
        },
        { passive: false }
      );
    },

    getCurrentTime() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 补零
      const day = String(date.getDate()).padStart(2, "0"); // 补零
      const hour = String(date.getHours()).padStart(2, "0"); // 补零
      const minute = String(date.getMinutes()).padStart(2, "0"); // 补零
      const second = String(date.getSeconds()).padStart(2, "0"); // 补零

      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 根据IP 定位  获取当前地理坐标位置
    async getLocation() {
      try {
        this.overShow = true;
        var that = this;
        // andronid原生定位
        if (window.plus) {
          plus.geolocation.getCurrentPosition(
            function(res) {
              console.log("res--地理位置-->", res);
              console.log("当前位置的经度：" + res.coords.longitude);
              console.log("JSON.stringify(res)---->", JSON.stringify(res));
              that.longitude = res.coords.longitude;
              console.log("当前位置的纬度：" + res.coords.latitude);
              that.latitude = res.coords.latitude;

              if (that.latitude && that.longitude) {
                    that.baseService
                      .get(
                        `https://apis.map.qq.com/ws/geocoder/v1/?location=${that.latitude},${that.longitude}&key=46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5`
                      )
                      .then(res => {
                        console.log(
                          "res-根据IP获取到地址定位--逆解析为正常地址--->",
                          res
                        );

                        that.currenntAddress = res.result.address;
                        console.log(
                          "currenntAddress:逆解析为正常地址:: ",
                          that.currenntAddress
                        );
                          that.initMap();
                      })
                      .catch(error => {
                        console.error("获取打卡位置异常:", error);
                        that.$toast.fail("当前位置逆解析失败");
                      });
              } else {
                console.log("获取位置失败：");
              }
            },

            function(err) {
              console.log("获取位置失败：" + JSON.stringify(err));
            }
          );
        } else {
          console.log("获取plus对象失败：");
        }

        //#region 线上的定位环境
        // todo 线上环境
        // this.baseService
        //   .get(
        //     "https://apis.map.qq.com/ws/location/v1/ip?key=46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5"
        //   )
        //   .then(res => {
        //     console.log(
        //       "res.result.location---->",
        //       JSON.stringify(res.result.location)
        //     );
        //     let currenntPoint = res.result.location;
        //     console.log("currenntPoint::111: ", currenntPoint);
        //     this.longitude = currenntPoint.lng;
        //     this.latitude = currenntPoint.lat;
        //     this.baseService
        //       .get(
        //         `https://apis.map.qq.com/ws/geocoder/v1/?location=${currenntPoint.lat},${currenntPoint.lng}&key=46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5`
        //       )
        //       .then(res => {
        //         console.log(
        //           "res-根据IP获取到地址定位--逆解析为正常地址--->",
        //           res
        //         );

        //         this.currenntAddress = res.result.address;
        //         console.log(
        //           "currenntAddress:逆解析为正常地址:: ",
        //           this.currenntAddress
        //         );
        //         // 定位结束后 初始化地图
        //         if (this.longitude && this.latitude) {
        //           this.initMap();
        //         }
        //       })
        //       .catch(error => {
        //         console.error("获取打卡位置异常:", error);
        //         this.$toast.fail("请求失败");
        //       });
        //   });
        //#endregion

        //#region pc 端测试定位的环境
        // const response = await MapClient.get("/ws/location/v1/ip", {
        //   params: {
        //     key: "46SBZ-PJUCT-6REXJ-L5BKO-WQCEE-6MBA5"
        //   }
        // });
        // // console.log("地图数据:", response.data);
        // let currenntPoint = response.data.result.location;
        // console.log("currenntPoint::: ", currenntPoint);
        // this.longitude = currenntPoint.lng;
        // this.latitude = currenntPoint.lat;
        // if (this.longitude && this.latitude) {
        //   this.initMap();
        // }
        //#endregion
      } catch (error) {
        console.error("地图请求失败:", error);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.page-point-clock {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(to right, #cee7ff, #a5d3ff);
  // 禁止y轴 滑动
  overflow: hidden; /* 禁止内容溢出 */
  touch-action: pan-x; /* 只允许横向滑动，禁止纵向滑动 */
}
#map-container {
  width: 100%;
  height: 100%;
}

.user-active-btn {
  z-index: 999999;
  position: absolute;
  bottom: 0px;
  display: flex;
  width: 100%;
  height: 60px;
  justify-content: space-evenly;
  background-color: white;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  font-family: "PingFang SC", sans-serif;
}
.user-active-btn-item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  padding: 8px 0;
  gap: 4px; //
}
/deep/ .van-button {
  border: none;
}
.van-button__text {
  color: white;
}

.van-button {
  width: 90%;
  max-width: 160px;
  border-radius: 30px;
  padding: 8px 16px;
  font-size: 15px;
  font-weight: bold;
  background: linear-gradient(to right, #4eabff, #3a8cff);
  color: white;
  transition: transform 0.2s ease;
}
.tip-text {
  color: #666;
  padding: 6px 22px;
}
.van-button:active {
  transform: scale(0.97); // 点击时轻微缩放，增加交互感
}
/deep/ .rotate-circle {
  display: none;
}
/deep/ .tmap-zoom-control {
  display: none;
}
/deep/ .tmap-scale-control {
  display: none;
}

/deep/ .van-calendar__text {
  position: relative; /* 确保伪元素以它为基准定位 */
}

/deep/ .addBlueDotLeft::after {
  content: "";
  position: absolute;
  left: 40%; /* 水平居中 */
  bottom: 10px; /* 在文字正下方，根据圆点大小调整 */
  transform: translateX(-50%); /* 精确水平居中 */
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #3794ff;
}

/deep/ .addBlueDotRight::before {
  content: "";
  position: absolute;
  left: 60%;
  bottom: 10px;
  transform: translateX(-50%);
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #3794ff;
}
/deep/ .addRedDotLeft::after {
  content: "";
  position: absolute;
  left: 40%;
  bottom: 10px;
  transform: translateX(-50%);
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #ff0000;
}

/deep/ .addRedDotRight::before {
  content: "";
  position: absolute;
  left: 60%;
  bottom: 10px;
  transform: translateX(-50%);
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #ff0000;
}
.new-clock {
  // z-index: 1;
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: #cee7ff;
  background-image: linear-gradient(to right, #cee7ff, #a5d3ff);
  margin-top: 3px;

  .user-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    background-color: #ffffff; // 白色背景
    border-radius: 8px; // 圆角边框
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); // 轻微阴影
    padding: 6px 10px;
    .user-info-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .user-avatar {
      width: 48px;
      height: 48px;
      border-radius: 10%;
      overflow: hidden;
      margin-right: 12px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .user-name {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
    .user-action {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      img {
        width: 20px;
      }
      span {
        font-size: 12px;
        color: #333;
      }
    }
  }

  .clock-detail {
    margin-bottom: 20px;
    background-color: #ffffff; // 白色背景
    border-radius: 8px; // 圆角边框
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); // 轻微阴影

    .clock-time {
      display: flex;
      justify-content: space-between;
      .clock-time-item {
        display: flex;
      }
      .detail-item {
        display: flex;
        flex: 1;
        flex-direction: column;
        margin: 0 12px;
        background-color: #ececee;
        justify-content: start;
        margin-top: 10px;
        border-radius: 6px;
        padding: 2px 10px;
        .label {
          font-size: 14px;
          color: #333;
        }

        .value {
          font-size: 14px;
          color: #333;
        }
      }
    }
    .today-clock-time {
      display: flex;
      align-items: center;
      .today-clock-time-text {
        font-size: 12px;
        color: #666;
      }
    }

    .clock-action {
      width: 100%;
      height: 58vh;
    }
  }
}
.clock-action {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 20px;

  .clock-button {
    width: 180px;
    height: 180px;
    border-radius: 50%;
    background: linear-gradient(135deg, #4eabff, #3a8cff);
    color: white;
    font-size: 16px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    margin-bottom: 16px;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.95);
    }
  }

  .location-info {
    text-align: center;

    p {
      margin: 4px 0;
      font-size: 14px;
    }

    .in-range {
      color: green;
    }

    .out-range {
      color: red;
    }
  }
}
.active-bottom-nav {
  background: linear-gradient(145deg, #4eabff, #3a8cff);
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1),
    inset 0 -1px 3px rgba(255, 255, 255, 0.2); // 内凹高光感
  padding: 6px 22px;
  border-radius: 24px;
  font-weight: bold;
  position: relative;
  overflow: hidden;

  // 添加轻微点击反馈（可选）
  &:active {
    transform: scale(0.97);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1),
      inset 0 1px 3px rgba(255, 255, 255, 0.3);
  }
}
.user-work-no {
  font-size: 12px;
  color: #333;
}
.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 16px;

  .record-item {
    margin-bottom: 12px;
    border: 1px solid #eee;
    border-radius: 8px;
    padding: 12px;
    background-color: #f9f9f9;

    .record-title {
      font-weight: bold;
      font-size: 15px;
      color: #333;
    }

    .record-details {
      margin-top: 8px;
      font-size: 13px;
      color: #666;

      p {
        margin: 4px 0;
      }
    }
  }

  .no-record {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
  }
}
.time-display {
  font-size: 14px;
}
</style>
